package com.book.dao.Impl;

import com.book.utils.jdbcUtil;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public abstract class baseDao {
    private QueryRunner queryRunner=new QueryRunner();

    /**
     * 更新操作
     * @param sql
     * @param args
     * @return
     */
    public int update(String sql,Object...args){
        Connection conn= jdbcUtil.getConnection();
        try {
            return queryRunner.update(conn,sql,args);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            try {
                DbUtils.close(conn);
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        return -1;
    }

    /**
     * 查找一个对象
     * @param type
     * @param args
     * @param <T>
     * @return 返回一个bean对象
     */
    public<T> T queryForOne(Class<T> type,String sql,Object...args){
        Connection conn= jdbcUtil.getConnection();
        try {
            return queryRunner.query(conn, sql, new BeanHandler<T>(type),args);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            try {
                DbUtils.close(conn);
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 查找多个对象
     * @param type
     * @param sql
     * @param args
     * @param <T>
     * @return 返回多个bean对象
     */
    public<T> List<T>  queryForList(Class<T> type, String sql, Object...args){
        Connection conn = jdbcUtil.getConnection();
        try {
            return queryRunner.query(conn, sql, new BeanListHandler<T>(type), args);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            try {
                DbUtils.close(conn);
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        return null;
    }

    /**
     *
     * @param sql
     * @param args
     * @return 返回聚合函数一类的值
     */
    public Object queryCount(String sql,Object...args){
        Connection conn = jdbcUtil.getConnection();
        try {
            return queryRunner.query(conn, sql, new ScalarHandler(), args);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            try {
                DbUtils.close(conn);
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        return null;
    }
}
